package com.jcode.netty.protocol;

import java.io.Serializable;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Desc
 * @Author dreajay
 * @DateTime 2016年10月15日 上午10:24:04
 */
public class PacketUtil {

    private static final AtomicLong sequence = new AtomicLong(1);

    /**
     * 构建请求包
     *
     * @param cmd
     *
     * @return
     *
     * @throws Exception
     */
    public static Packet createRequestPacket(int cmd) throws Exception {
        return createRequestPacket(cmd, null);
    }

    /**
     * 构建请求包
     *
     * @param cmd
     * @param body
     *
     * @return
     *
     * @throws Exception
     */
    public static Packet createRequestPacket(int cmd, Serializable body) {
        Packet packet = new Packet();
        packet.setCmd(cmd);
        packet.setSequenceId(sequence.getAndIncrement());
        packet.setBody(body);
        return packet;
    }

    /**
     * 构建响应包
     *
     * @param request
     * @param cmd
     *
     * @return
     *
     * @throws Exception
     */
    public static Packet createResponsePacket(Packet request, int cmd) {
        return createResponsePacket(request, cmd);
    }

    /**
     * 构建响应包
     *
     * @param request
     * @param body
     *
     * @return
     *
     * @throws Exception
     */
    public static Packet createResponsePacket(Packet request, int cmd, Serializable body) {
        Packet packet = new Packet();
        packet.markResponseType();
        packet.setCmd(cmd);
        packet.setSequenceId(request.getSequenceId());
        packet.setBody(body);
        return packet;
    }

    public static void main(String[] args) throws Exception {
        HashMap<String, String> user = new HashMap<String, String>();
        user.put("user", "222");
        Packet packet = createRequestPacket(1000, user);

    }
}
